// BuddyListDlg.cpp : implementation file
//
#include "stdafx.h"
#include "firstClient.h"
#include "BuddyListDlg.h"
using namespace std;

IMPLEMENT_DYNAMIC(CBuddyListDlg, CDialog)

CBuddyListDlg::CBuddyListDlg(CWnd* pParent, IAccSession* S)
	: CDialog(CBuddyListDlg::IDD, pParent), m_session(S)
{
		S->get_BuddyList(&m_bL);
		m_profileWrap = gcnew ProfileWrapper::ProfileWrapper();
}

CBuddyListDlg::~CBuddyListDlg()
{
}

BOOL CBuddyListDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	//load images to use next to buddies
	CBitmap bm;
	m_imageList.Create(16,16,ILC_COLOR16,0,4);
	bm.LoadBitmapW(IDB_STATES);
	m_imageList.Add(&bm,RGB(0,0,0));
	m_display.SetImageList(&m_imageList,TVSIL_NORMAL);
	return true;
}

void CBuddyListDlg::loadBuddyList()
{
	xp_int num;
	m_bL->get_GroupCount(&num);
	for(int i=0;i<num;i++)
	{
		CComPtr<IAccGroup> grp;
		m_bL->GetGroupByIndex(i,&grp);
		getBuddies(grp);
	}
}

void CBuddyListDlg::getBuddies(IAccGroup *grp)
{
	xp_int num;
	grp->get_BuddyCount(&num);
	xp_str grp_nm;
	grp->get_Name(&grp_nm);
	for(int i=0;i<num;i++)
	{
		CComPtr<IAccUser> usr;
		grp->GetBuddyByIndex(i,&usr);
		xp_str nm; 
		usr->get_Name(&nm);
		CComVariant st;
        usr->get_Property(AccUserProp_State, &st);
        xp_int state = st.intVal;
		if(state >= AccUserState_Online) //online,idle, or away
		{
			addBuddy(nm, grp_nm,state);
		}
	}
}
void CBuddyListDlg::addBuddy(xp_str name,xp_str grp, xp_int state )
{
	ASSERT(m_display);
	HTREEITEM prt;
	//int imageNum = (state & AccUserState_Away) ? 2 : ((state & AccUserState_Idle) ? 1:0);
	if(m_groups.find(grp) == m_groups.end())
	{
		TVINSERTSTRUCT in;
		in.hInsertAfter = NULL; in.hParent = NULL;
		in.item.mask = TVIF_TEXT;
		in.item.pszText = grp;
		prt = m_display.InsertItem(&in);
		m_groups[grp] = prt;
	}
	else
	{
		prt = m_groups[grp];
	}
	m_display.Expand(prt,TVE_EXPAND);
	m_display.InsertItem(name,state,state,prt);
}

void CBuddyListDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_TREE1, m_display);
}

void CBuddyListDlg::OnBnClickRefresh()
{
	loadBuddyList();
}

BEGIN_MESSAGE_MAP(CBuddyListDlg, CDialog)
	ON_BN_CLICKED(ID_REFRESH, &CBuddyListDlg::OnBnClickRefresh)
	ON_NOTIFY(TVN_SELCHANGED, IDC_TREE1, &CBuddyListDlg::OnTvnSelchangedTree1)
END_MESSAGE_MAP()


// CBuddyListDlg message handlers

void CBuddyListDlg::OnTvnSelchangedTree1(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
	HTREEITEM item = m_display.GetSelectedItem();
	CString selected = m_display.GetItemText(item);
	
	System::String^ sel = gcnew System::String(selected);
	m_profileWrap->showProfile(sel);
	*pResult = 0;
}
